package com.qfedu.yanglao20admin.companion.service.Impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qfedu.yanglao20.common.constants.CommonConstants;
import com.qfedu.yanglao20.common.exeception.CommonException;
import com.qfedu.yanglao20.entity.companion.Companion;
import com.qfedu.yanglao20admin.companion.dao.CompanionDao;
import com.qfedu.yanglao20admin.companion.param.CompanionParam;
import com.qfedu.yanglao20admin.companion.service.CompanionService;
import com.qfedu.yanglao20admin.companion.vo.CompanionCommonVO;
import com.qfedu.yanglao20admin.companion.vo.CompanionVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service
public class CompanionServiceImpl implements CompanionService {

    @Resource
    private CompanionDao companionDao;


    @Override
    public Page<CompanionVO> pageCompanion(CompanionParam param) {
        Page<CompanionVO> page = new Page<>(param.getPageNum(), param.getPageSize());
        List<CompanionVO> companionVOS = companionDao.selectList(param);


        page.setCurrent(param.getPageNum());
        page.setSize(param.getPageSize());
        page.setRecords(companionVOS);

        Long aLong = companionDao.selectCount(null);
        page.setTotal(aLong);

        return page;
    }

    @Override
    public void addCompanion(CompanionCommonVO companionCommonVO) {
        if (companionCommonVO.getUsername() == null || companionCommonVO.getUsername().isEmpty()) {
            throw new CommonException(CommonConstants.ERROR, "请写入用户名");
        }

        CompanionCommonVO userName = companionDao.selectByUserName(companionCommonVO.getUsername());
        if (userName != null) {
            throw new CommonException(CommonConstants.ERROR, "该用户名已存在");
        }

        companionDao.insertCompanion(companionCommonVO);
    }

    @Override
    public void deleteById(Integer id) {
        companionDao.deleteById(id);
    }

    @Override
    public Companion queryCompanion(Integer id) {
        return companionDao.selectByCompanionId(id);
    }

    @Override
    public void updateCompanion(CompanionCommonVO companionCommonVO) {
        if (companionCommonVO.getUsername() == null || companionCommonVO.getUsername().isEmpty()) {
            throw new CommonException(CommonConstants.ERROR, "请写入用户名");
        }

        CompanionCommonVO userName = companionDao.selectByUserName(companionCommonVO.getUsername());
        if (userName != null) {
            if (!userName.getId().equals(companionCommonVO.getId())) {
                throw new CommonException(CommonConstants.ERROR, "该用户名已存在");
            }
        }

        companionDao.updateCompanion(companionCommonVO);
    }
}
